package com.grad.webstudy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.grad.webstudy.context.UserContext;
import com.grad.webstudy.dao.HistoryDao;
import com.grad.webstudy.enums.ExceptionEnums;
import com.grad.webstudy.exceptions.CustomException;
import com.grad.webstudy.model.History;
import com.grad.webstudy.model.User;
import com.grad.webstudy.service.CourseDetailService;
import com.grad.webstudy.service.CourseService;
import com.grad.webstudy.service.HistoryService;
import com.grad.webstudy.vo.CourseVo;
import com.grad.webstudy.vo.HistoryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Description:
 * @Author: zjf
 * @Date: 2020/2/3 16:10.
 */

@Service
@Transactional
public class HistoryServiceImpl implements HistoryService {

    @Autowired
    private HistoryDao historyDao;


    @Autowired
    private CourseDetailService courseDetailService;

    @Autowired
    private CourseService courseService;

    @Override
    public PageInfo queryAllByPage(int currPage, int pageSize) {

        User loginUser = UserContext.getLoginUser();

        Page page = PageHelper.startPage(currPage, pageSize);
        PageInfo<HistoryVo> result = new PageInfo<>(trans2Vo(historyDao.queryAll(loginUser.getId())));

        result.setTotal(page.getTotal());
        result.setPageNum(currPage);
        result.setPageSize(pageSize);
        return result;
    }

    @Override
    public boolean deleteHistories(String ids) {
        List<String> deleteId = Arrays.asList(ids.split(","));
        if (deleteId.size() <= 0) {
            throw new CustomException(ExceptionEnums.CUSTOM_ERROR.getCode(),
                    "传入的参数ids【" + ids + "】有误");
        }
        return historyDao.deleteIds(deleteId) == deleteId.size();
    }

    @Override
    public boolean userHistory(Integer courseDetailId, Integer progress) {

        Integer courseId = courseDetailService.queryCourseIdByDetailId(courseDetailId);
        User loginUser = UserContext.getLoginUser();
        History userHistory = historyDao.checkHistory(courseDetailId, loginUser.getId());
        History history = new History();
        history.setCourseDetailId(courseDetailId);
        history.setCourseId(courseId);
        history.setUserId(loginUser.getId());
        history.setProgress(progress == null ? 0 : progress);
        if (Objects.nonNull(userHistory)) {
            //如果不为空，代表存在这条历史记录，则更新
            historyDao.updateHistory(history);
            return true;
        } else {
            history.setAddTime(new Date());
            historyDao.insert(history);
            return true;
        }

    }

    @Override
    public List<History> queryCourseHistoryByCurrUser(Integer courseId) {
        User loginUser = UserContext.getLoginUser();
        Integer userId = loginUser.getId();
        return historyDao.getCourseHistory(userId, courseId);
    }

    @Override
    public History queryCourseDetailHistory(Integer courseDetailId, Integer userId) {
        return historyDao.checkHistory(courseDetailId, userId);
    }


    private List<HistoryVo> trans2Vo(List<History> histories) {
        Set<History> historySet = new TreeSet<>((o1, o2) -> o1.getCourseId().compareTo(o2.getCourseId()));
        historySet.addAll(histories);

        List<HistoryVo> result = new ArrayList<>(historySet.size());
        for (History history : historySet) {
            HistoryVo historyVo = new HistoryVo(history);
            CourseVo courseVo = courseService.queryById(history.getCourseId(),null);
            historyVo.setCoverPath(courseVo.getCoverPath());
            historyVo.setClassName(courseVo.getClassName());
            historyVo.setProgress(courseVo.getProgress());
            result.add(historyVo);
        }
        return result;
    }
}
